<template>
  <div class="file-upload-container">
    <el-upload
      :file-list="fileList"
      :http-request="httpRequest"
      :limit="5"
      :accept="'.xlsx,.doc,.docx,.ppt,.pptx,.txt,.png,.jpg,.jpeg'"
      :on-exceed="handleExceed"
      :on-error="handleError"
      class="upload-demo"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">点击或者拖拽文件到此处上传</div>
      <template #tip>
        <div class="el-upload__tip">
          只能上传xlsx、word、ppt、txt、png、jpg、jpeg文件，且最多只能上传5个文件
        </div>
      </template>
      <!-- 自定义文件展示 -->
      <template #file="{ file }">
        <div class="custom-file-item">
          <!-- 根据文件名的扩展名展示不同的图标 -->
          <el-icon v-if="isExcel(file.name)" class="file-icon">
            <span class="iconfont icon-Excel"  style="font-size: 20px;color: #3da54d"></span>
          </el-icon>
          <el-icon v-else-if="isWord(file.name)" class="file-icon">
            <span class="iconfont icon-Word"  style="font-size: 20px;color: #409EFF"></span>
          </el-icon>
          <el-icon v-else-if="isPPT(file.name)" class="file-icon">
            <span class="iconfont icon-ppt"  style="font-size: 20px;color: #e64a19"></span>
          </el-icon>
          <el-icon v-else-if="isTxt(file.name)" class="file-icon">
            <span class="iconfont icon-wenjian_txt"  style="font-size: 20px;color: #409EFF"></span>
          </el-icon>
          <el-icon v-else-if="isImage(file.name)" class="file-icon">
            <span class="iconfont icon-img" style="font-size: 20px;color: #74b3f8"></span>
          </el-icon>
          <span class="file-name">{{ file.name }}</span>
          <!-- 添加删除按钮 -->
          <el-icon class="delete-icon" @click.stop="deleteFile(file)">
            <delete-filled />
          </el-icon>

          <a :href="file.url" :download="file.name" target="_blank">  <el-icon class="Download-icon" @click.stop="DownloadFile(file)">
            <Download />
          </el-icon>
          </a>

        
        </div>
      </template>
    </el-upload>

    <!-- <el-button type="primary" @click="uploadFiles">上传附件</el-button> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { UploadRequestOptions, UploadFile } from 'element-plus';
import { UploadFilled, Document, Picture, Share, Lightning, Paperclip, DeleteFilled } from '@element-plus/icons-vue';
import { uploadMealPicture, uploadEmpFile } from '@/api/employee';
import { compressImageToBase64 } from '@/utils/file';
import { useEmployeeStore } from '@/stores/employee';

const employeeStore = useEmployeeStore();
const fileList = ref<UploadFile[]>([]);

const props = defineProps({
  userid: {
    type: String,
    required: true
  },
  isEdit: {
    type: Boolean,
    required: true
  },
  employeeType: {
    type: String,
    required: true
  }
});
// 在组件挂载时从 Pinia 获取附件信息并回显
onMounted(() => {  
  getDatas()
  
});

const getDatas=()=>{
  const employeeInfo = employeeStore.employeeInfo;
  if (employeeInfo && employeeInfo.file && Array.isArray(employeeInfo.file)) {
    fileList.value = employeeInfo.file.map((item: { file_name: any; file_url: any; }) => ({
      name: item.file_name,
      url: item.file_url
    }));
  }
}



// 修改employeeStore.employeeInfo
const changeStoreData=()=>{
  let employeeInfo = employeeStore.employeeInfo;  
  
  if (fileList.value && fileList.value.length>0 && Array.isArray(fileList.value)) {
    employeeInfo.file = fileList.value.map(item=>({
      file_name:item.name,
      file_url:item.url
    }))
  }
  employeeStore.setEmployeeInfo(employeeInfo)

  
  if (fileList.value && fileList.value.length>0 && Array.isArray(fileList.value)) {
    fileList.value = fileList.value.map(item=>({
      name:item.name,
      url:item.url
    }))
  }
}




// 自定义文件类型的判断函数
const isExcel = (fileName: string) => fileName.toLowerCase().endsWith('.xlsx') || fileName.toLowerCase().endsWith('.xls');
const isWord = (fileName: string) => fileName.toLowerCase().endsWith('.docx') || fileName.toLowerCase().endsWith('.doc');
const isPPT = (fileName: string) => fileName.toLowerCase().endsWith('.pptx') || fileName.toLowerCase().endsWith('.ppt');
const isTxt = (fileName: string) => fileName.toLowerCase().endsWith('.txt');
const isImage = (fileName: string) => ['.png', '.jpg', '.jpeg'].some(ext => fileName.toLowerCase().endsWith(ext));

// 删除文件
const deleteFile =async (file: UploadFile) => {

  const index = fileList.value.findIndex(f => f.name === file.name && f.url === file.url);
  if (index !== -1) {
    fileList.value.splice(index, 1);
    // ElMessage.success(`文件 ${file.name} 已删除`);
  }
  
  try {
    let params = {
      userid: props.userid, // 这里使用固定的 userid，实际应用中可以动态获取
      empfile: fileList.value.map(file => ({
        file_name: file.name,
        file_url: file.url
      }))
    };

    // console.log(params);
    // params.empfile=[]
    
    const response = await uploadEmpFile(params);
    if (response.code === '200') {
      changeStoreData()
      ElMessage.success('文件删除成功');
    } else {
      ElMessage.error('文件删除失败');
    }
  } catch (error) {
    ElMessage.error('文件删除失败');
  }
};


//下载文件
const DownloadFile= async(file: UploadFile) => {
  console.log(file);
  // downLoadFile(file.url,file.name)
}


	// function downLoadFile (Fileurl: string |any,FileName: any){
  //     let fileName = FileName; // 这里是通过从后端获取到的 url  地址中截出来原本的文件名
  //     fetch(Fileurl)
  //       .then((res) => res.blob())
  //       .then((blob) => {
  //         const link = document.createElement('a');
  //         link.href = URL.createObjectURL(blob);
  //         // 下载文件的名称及文件类型后缀
  //         link.download = fileName;
  //         document.body.appendChild(link);
  //         link.click();
  //         //在资源下载完成后 清除 占用的缓存资源
  //         window.URL.revokeObjectURL(link.href);
  //         document.body.removeChild(link);
  //       });
	// }
	




// 上传文件到新接口
const uploadFiles = async () => {
  if (!fileList.value.length) {
    ElMessage.error('请先选择文件');
    return;
  }

  try {
    const params = {
      userid: props.userid, // 这里使用固定的 userid，实际应用中可以动态获取
      empfile: fileList.value.map(file => ({
        file_name: file.name,
        file_url: file.url
      }))
    };

    const response = await uploadEmpFile(params);
    if (response.code === '200') {
      changeStoreData()
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    ElMessage.error('文件上传失败');
  }
};

// 文件上传请求
async function httpRequest(options: UploadRequestOptions) {
  const allowedExtensions = ['xlsx', 'doc', 'docx', 'ppt', 'pptx', 'txt', 'png', 'jpg', 'jpeg'];
  const fileExtension = options.file.name.split('.').pop()?.toLowerCase();

  if (!allowedExtensions.includes(fileExtension as string)) {
    ElMessage.error(`文件格式不支持：${options.file.name}`);
    return;
  }

  try {
    if (['png', 'jpg', 'jpeg'].includes(fileExtension as string)) {
      const compressedBase64 = await compressImageToBase64(options.file);
      const pictureBase64Data = compressedBase64.split(',')[1];
      const { result } = await uploadMealPicture(pictureBase64Data, options.file.name);

      if (result) {
         fileList.value.push({ name: options.file.name, url: result });
      }
      await uploadFiles()
    } else {
      const reader = new FileReader();
      reader.onload = async (e) => {
        if (e.target?.result) {
          const base64Data = e.target.result.toString().split(',')[1];
          const { result } = await uploadMealPicture(base64Data, options.file.name);

          if (result) {
            fileList.value.push({ name: options.file.name, url: result });
          }
          await uploadFiles()
        }
      };
      reader.readAsDataURL(options.file);
    }
    
  } catch (error) {
    ElMessage.error('上传出错');
  }
}

// 文件数量超出限制时的处理
function handleExceed(files: File[], uploadFiles: UploadFile[]) {
  ElMessage.error(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + uploadFiles.length} 个文件`);
}

// 文件上传出错时的处理
function handleError(err: Error, file: UploadFile, uploadFiles: UploadFile[]) {
  ElMessage.error(`上传文件 ${file.name} 出错：${err.message}`);
}
</script>

<style scoped>
.custom-file-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.file-icon {
  margin-right: 10px;
}

.file-name {
  flex: 1;
}

.delete-icon {
  margin-left: 10px;
  cursor: pointer;
  color: #f56c6c;
}
.Download-icon {
  margin-left: 10px;
  cursor: pointer;
  color: #2dda16;
}

</style>